package com.qf.talk.service.impl;

import com.qf.talk.dao.FriendRelationDao;
import com.qf.talk.dao.MessageDao;
import com.qf.talk.model.FriendRelation;
import com.qf.talk.model.FriendRelationExample;
import com.qf.talk.model.Message;
import com.qf.talk.service.TalkService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class TalkServiceimpl implements TalkService {
    @Resource
    private FriendRelationDao friendRelationDao;
    @Resource
    private MessageDao messageDao;
    @Override
    public int sendMessage(Long userId, Long toUserId, String message, Integer MessageType) {
        //发送消息的逻辑
        //校验是否存在好友关系
        //比如
        //useriD--张三
        //touserid --李四
        //张三给李四发送消息，需要判断李四是否把张三删除了
        FriendRelationExample example=new FriendRelationExample();
        FriendRelationExample.Criteria criteria = example.createCriteria();
        criteria.andFriendIdEqualTo(userId);
        criteria.andUserIdEqualTo(toUserId);
        List<FriendRelation> friendRelations = friendRelationDao.selectByExample(example);
        if (!(friendRelations!=null&&friendRelations.size()>0)){
            //张三不能给李四发消息
            return -1;
        }
        //2把消息存放到数据库中
        Message msg=new Message();
        msg.setMessage(message);
        msg.setMessageTypeId(MessageType);
        msg.setSendTime(new Date(System.currentTimeMillis()));
        msg.setSendUserId(userId);
        msg.setReceiveUserId(toUserId);
        msg.setReadState(0);
        int insert = messageDao.insert(msg);


        return insert;

    }
}
